﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Globalization;

namespace ESOL.Common
{
    public class CommonFunctions
    {
        public static bool IsNumeric(string pValue)
        {
            if (pValue == null || pValue.Trim() == "")
            {
                return false;
            }
            string numeric = "-0123456789";
            for (int i = 0; i < pValue.Length; i++)
            {
                string character = pValue.Substring(i, 1);
                if (numeric.IndexOf(character) >= 0)
                {
                    continue;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }

        public static bool IsDecimal(string pValue)
        {
            if (pValue == null || pValue.Trim() == "")
            {
                return false;
            }
            string numeric = "-0123456789.";
            for (int i = 0; i < pValue.Length; i++)
            {
                string character = pValue.Substring(i, 1);
                if (numeric.IndexOf(character) >= 0)
                {
                    continue;
                }
                else
                {
                    return false;
                }
            }
            return true;
        }

        public static decimal ToDecimal(object oValue)
        {
            if (oValue == null)
            {
                return 0;
            }
            if (string.IsNullOrEmpty(oValue.ToString()))
            {
                return 0;
            }
            if (IsDecimal(oValue.ToString()) == false)
            {
                return 0;
            }
            return Convert.ToDecimal(oValue.ToString());
        }

        public static int ToInt32(object oValue)
        {
            if (oValue == null)
            {
                return 0;
            }
            if (string.IsNullOrEmpty(oValue.ToString()))
            {
                return 0;
            }
            if (IsNumeric(oValue.ToString()) == false)
            {
                return 0;
            }
            return Convert.ToInt32(oValue.ToString());
        }

        public static string ToString(object oValue)
        {
            if (oValue == null)
            {
                return "";
            }
            return Convert.ToString(oValue);
        }

        public static object ToObject(object oValue)
        {
            if (oValue == null)
            {
                return null;
            }
            if (oValue.ToString().Trim() == "")
            {
                return null;
            }
            return oValue;
        }

        public static string GetSelect(string rowCount)
        {
            if (string.IsNullOrEmpty(rowCount) == false && IsNumeric(rowCount))
            {
                return " SELECT TOP " + rowCount + " ";
            }
            return " SELECT ";
        }

        public static string GetFileExtension(string sFile)
        {
            if(string.IsNullOrEmpty(sFile))
                return null;
            string[] sTemp=sFile.Split('.');
            return sTemp[sTemp.Length-1];
        }

        public static string GetFileNoExtension(string sFile)
        {
            if (string.IsNullOrEmpty(sFile))
                return null;
            string[] sTemp = sFile.Split('.');
            return sTemp[sTemp.Length - 1];
        }

        public static string GetFilePrefix(string sFullFileName)
        {
            if (string.IsNullOrEmpty(sFullFileName))
                return null;
            string[] sTemp=sFullFileName.Split('\\');
            return sTemp[sTemp.Length - 1];
        }

        public static Image byteArrayToImage(byte[] byteArrayIn)
        {
            try
            {
                MemoryStream ms = new MemoryStream(byteArrayIn);
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }
            catch(Exception ex)
            {
                return null;
            }
        }

        public static byte[] FileToByte(string fileName)
        {
            FileInfo fi = new FileInfo(fileName);
            FileStream fs = fi.OpenRead();
            byte[] bytes = new byte[fs.Length];
            fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
            return bytes;
        }

        /// <summary>
        /// 判断密码，是否符合密码规则
        /// 密码规则：至少有一个大写字母，一个小写字母，一个数字，一个特殊符号，密码长度最小为8位
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool CheckPassword(string password, out string errMsg)
        {
            errMsg = "";
            if (string.IsNullOrEmpty(password))
            {
                errMsg = "密码不能为空";
                return false;
            }
            if (password.Length < 8)
            {
                errMsg = "密码长度至少为8为";
                return false;
            }
            bool pass = false;
            string c = "abcdefghijklmnopqrstuvwxyz";
            for (int i = 0; i < password.Length; i++)
            {
                if (c.Contains(password[i]))
                {
                    pass = true;
                    break;
                }
            }
            if (!pass)
            {
                errMsg = "至少需要包含一个小写字母";
                return false;
            }
            pass = false;
            c = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            for (int i = 0; i < password.Length; i++)
            {
                if (c.Contains(password[i]))
                {
                    pass = true;
                    break;
                }
            }
            if (!pass)
            {
                errMsg = "至少需要包含一个大写字母";
                return false;
            }
            pass = false;
            c = "0123456789";
            for (int i = 0; i < password.Length; i++)
            {
                if (c.Contains(password[i]))
                {
                    pass = true;
                    break;
                }
            }
            if (!pass)
            {
                errMsg = "至少需要包含一个数字";
                return false;
            }
            pass = false;
            c = "~!@#$%^&*()_+";
            for (int i = 0; i < password.Length; i++)
            {
                if (c.Contains(password[i]))
                {
                    pass = true;
                    break;
                }
            }
            if (!pass)
            {
                errMsg = "至少需要包含一个特殊字符";
                return false;
            }
            return true;
        }

        public static string DateDiff(DateTime DateTime1, DateTime DateTime2)
        {
            string dateDiff = null;
            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            dateDiff = ts.Days.ToString() + "天" + ts.Hours.ToString() + "小時" + ts.Minutes.ToString() + "分钟" + ts.Seconds.ToString() + "秒";
            return dateDiff;
        }

        //验证IP地址格式
        public static bool IPCheck(string sIP)
        {
            string num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
            return Regex.IsMatch(sIP, ("^" + num + "\\." + num + "\\." + num + "\\." + num + "$"));
        }

        //验证URL格式
        public bool URLCheck(string sURL)
        {
            return Regex.IsMatch(sURL, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
        }

        //使用系统自带的图片查看器
        public static void OpenPicViewer(Image img)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            string fileName = System.IO.Path.GetTempPath()+Guid.NewGuid().ToString() + ".jpg";
            img.Save(fileName);
            process.StartInfo.FileName = fileName;
            process.StartInfo.Arguments = "rundll32.exe C:\\WINDOWS\\system32\\shimgvw.dll,ImageView_Fullscreen";
            process.StartInfo.UseShellExecute = true;
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            process.Start();
            process.Close();
        }

        //计算某个日期所在的周是当年的第几周
        public static int WeekOfYear(DateTime dt, CultureInfo ci)
        {
            return ci.Calendar.GetWeekOfYear(dt, ci.DateTimeFormat.CalendarWeekRule, ci.DateTimeFormat.FirstDayOfWeek);
        }
    }
}
